import React, { FC, MouseEvent } from "react";
import styles from "./EditCanvas.module.scss";
import classnames from "classnames";
import { useDispatch } from "react-redux";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import { getComponentConfByType } from "../../../components/QusetionComponent";
import useBindCanvasKey from "../../../hooks/useBindCanvasKey";
import {
  ComponentInfoType,
  changeSelectId,
} from "../../../store/componentsReducer";
import { Spin } from "antd";
import SortableContainer from "../../../components/DragSortable/SortableContainer";
import SortableItem from "../../../components/DragSortable/SortableItem";
import { moveComponent } from "../../../store/componentsReducer";

type PropsType = {
  loading: boolean;
};

const getComponent = (componentInfo: ComponentInfoType) => {
  const { type, props } = componentInfo;
  const componentConfig = getComponentConfByType(type);
  if (!componentConfig) return null;
  const { Component } = componentConfig;
  return <Component {...props} />;
};

const EditCanvas: FC<PropsType> = ({ loading }) => {
  //绑定快捷键
  useBindCanvasKey();

  //选中
  const dispatch = useDispatch();
  const handleClick = (event: MouseEvent, id: string) => {
    event.stopPropagation();
    dispatch(changeSelectId(id));
  };

  const { componentList, selectId } = useGetComponentInfo();
  if (loading) {
    return (
      <div style={{ textAlign: "center", marginTop: "40%" }}>
        <Spin></Spin>
      </div>
    );
  }
  //SortableContainer组件的items需要每个 item 的 id 属性
  const componentListWithId = componentList.map((c) => {
    return { ...c, id: c.fe_id };
  });
  //拖拽结束的行为
  const handleDragEnd = (oldIndex: number, newIndex: number) => {
    dispatch(moveComponent({ oldIndex, newIndex }));
  };
  return (
    <SortableContainer items={componentListWithId} onDragEnd={handleDragEnd}>
      <div className={styles["canvas"]}>
        {componentList
          .filter((c) => !c.isHidden)
          .map((c) => {
            const { fe_id, isLocked } = c;
            const wrapperDefaultClassName = styles["component-wrapper"];
            const selectedClassName = styles["selected"];
            const lockedClassName = styles["locked"];
            const wrapperClass = classnames({
              [wrapperDefaultClassName]: true,
              [selectedClassName]: fe_id === selectId,
              [lockedClassName]: isLocked,
            });
            return (
              <SortableItem key={fe_id} id={fe_id}>
                <div
                  className={wrapperClass}
                  onClick={(e) => handleClick(e, fe_id)}
                >
                  <div className={styles.component}>{getComponent(c)}</div>
                </div>
              </SortableItem>
            );
          })}
      </div>
    </SortableContainer>
  );
};

export default EditCanvas;
